<?php

namespace app\common\model\logic;

class PhotoModel
{
    public function __construct()
    {
        $this->curModel = model('dao.photo');
    }

    public function getListPage($data)
    {
        $page = getPageData(); //获取分页数据
        $where[] = ['id', '>', 0];
        if (isset($data['keyword']) && !empty($data['keyword'])) {
            $where[] = ['name|account|mobile', 'like', '%'.$data['keyword'].'%'];
        }
        $list = $this->curModel->where($where)->limit($page['start'], $page['limit'])->order('id desc')->all();
        if ($list->isEmpty()) {
            exception(lang('GET_ERROR'), 0, 'app\\common\\exception\\DataEmptyException');
        } else {
            $data['total'] = $this->curModel->where($where)->count();
            $data['list'] = $list;

            return $data;
        }
    }

    //保存添加
    public function saveAdd($data)
    {
        $imageArr = json_decode(htmlspecialchars_decode($data['img_list']), true);
        if (!is_dir('./zip/')) {
            mkdir('./zip/', 0777, true);
        }
        $zipName = '/zip/'.date('ymd').(time() % 360000).'.zip';
        $zip = new \ZipArchive();
        $zip->open('.'.$zipName, \ZipArchive::CREATE);
        foreach ($imageArr as &$ve) {
            $zip->addFile('.'.$ve);
        }
        $insertData['tag'] = rand(99, 999999);
        $insertData['file_path'] = $zipName;
        $insertData['status'] = 1;
        $result = $this->curModel->allowField(true)->isUpdate(false)->save($insertData);
        if ($result !== false) {
            $this->saveInfo($this->curModel->id, $imageArr);

            return     $insertData['tag'];
        } else {
            exception(lang('SAVE_ERROR'), 0, 'app\\common\\exception\\LogicException');
        }
    }

    //保存添加
    public function getPhotoInfo($data)
    {
        $photoRow = $this->curModel->where('tag', $data['tag'])->find();
        if (!empty($photoRow)) {
            $infoList = model('dao.photo_info')->where('photo_id', $photoRow['id'])->select();
            $imgArr = [];
            foreach ($infoList as $ve) {
                $imgArr[] = $ve['img_url'];
            }

            return $imgArr;
        } else {
            exception(lang('NOT_LIST'), 0, 'app\\common\\exception\\LogicException');
        }
    }

    private function saveInfo($id, $imgList)
    {
        $infoData = [];
        foreach ($imgList as $ve) {
            $row['photo_id'] = $id;
            $row['img_url'] = $ve;
            $row['status'] = 1;
            $infoData[] = $row;
        }
        model('dao.photo_info')->saveAll($infoData);
    }
}
